//
//  NBSpeedDashboardView.m
//  automobiledashboard
//
//  Created by 王建华 on 2025/9/26.
//

#import "NBSpeedDashboardView.h"

@interface NBSpeedDashboardView () <CAAnimationDelegate>

@property (nonatomic, strong) CAShapeLayer *backgroundArcLayer;
@property (nonatomic, strong) CAShapeLayer *speedArcLayer;
@property (nonatomic, strong) UILabel *speedLabel;
@property (nonatomic, strong) UILabel *unitLabel;
@property (nonatomic, strong) CAGradientLayer *gradientLayer;

@property (nonatomic, strong) CAShapeLayer *pointerLayer; // 新增：指针图层
@property (nonatomic, assign) BOOL hasPlayedStartupAnimation; // 标记是否已播放启动动画

@property (nonatomic, assign) CGFloat pointerLastValue;

@property (nonatomic, copy) void(^animationCompletion)(BOOL finished);

@end

@implementation NBSpeedDashboardView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupView];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        [self setupView];
    }
    return self;
}

- (void)setupView {
    _maxSpeed = 180.0f; // 默认最大速度20km/h
    
    // 设置背景色
    self.backgroundColor = [UIColor clearColor];
    
    // 创建渐变层（右侧透明度渐变）
    [self createGradientLayer];
    
    // 创建背景圆弧
    [self createBackgroundArc];
    
    // 创建速度圆弧
    [self createSpeedArc];
    // 创建速度标签
    [self createSpeedLabel];
    
    // 创建单位标签
    [self createUnitLabel];
    
    // 确保在创建标签之前创建指针
    [self createPointer];
}

- (void)createGradientLayer {
    _gradientLayer = [CAGradientLayer layer];
    _gradientLayer.frame = self.bounds;
    _gradientLayer.type = kCAGradientLayerRadial; // 径向渐变
    
    // 从中心向外渐变
    _gradientLayer.startPoint = CGPointMake(0.5, 0.5); // 中心点
    _gradientLayer.endPoint = CGPointMake(1.0, 1.0);   // 向外扩散
    
    if (isPad) {
        
        _gradientLayer.colors = @[
            (id)[[UIColor colorWithWhite:0.0 alpha:1.] CGColor],    // 中心较深
            (id)[[UIColor colorWithWhite:0.0 alpha:0.895] CGColor],    // 中间
            (id)[[UIColor colorWithWhite:0.0 alpha:0.0] CGColor],     // 边缘透明
            (id)[[UIColor colorWithWhite:0.0 alpha:0.0] CGColor]
        ];
        
        _gradientLayer.locations = @[@0.0, @0.705, @0.865, @0 ];
    }else {
        
        _gradientLayer.colors = @[
            (id)[[UIColor colorWithWhite:0.0 alpha:1.] CGColor],    // 中心较深
            (id)[[UIColor colorWithWhite:0.0 alpha:0.615] CGColor],    // 中间
            (id)[[UIColor colorWithWhite:0.0 alpha:0.0] CGColor],     // 边缘透明
            (id)[[UIColor colorWithWhite:0.0 alpha:0.0] CGColor]
        ];
        
        _gradientLayer.locations = @[@0.0, @0.705, @0.865, @0 ];
    }
    [self.layer addSublayer:_gradientLayer];
}

- (void)createBackgroundArc {
    _backgroundArcLayer = [CAShapeLayer layer];
    _backgroundArcLayer.fillColor = [UIColor clearColor].CGColor;
    _backgroundArcLayer.strokeColor = [UIColor colorWithWhite:1.0 alpha:0.3].CGColor;
    _backgroundArcLayer.lineWidth = 8.0;
    _backgroundArcLayer.lineCap = kCALineCapRound;
    
    [self.layer addSublayer:_backgroundArcLayer];
}

- (void)createSpeedArc {
    _speedArcLayer = [CAShapeLayer layer];
    _speedArcLayer.fillColor = [UIColor clearColor].CGColor;
    _speedArcLayer.strokeColor = [UIColor whiteColor].CGColor;
    _speedArcLayer.lineWidth = 8.0;
    _speedArcLayer.lineCap = kCALineCapRound;
    _speedArcLayer.strokeEnd = 0.0;
    
    [self.layer addSublayer:_speedArcLayer];
}

- (void)createPointer {
    // 创建指针图层
    _pointerLayer = [CAShapeLayer layer];
    _pointerLayer.fillColor = [UIColor redColor].CGColor; // 红色填充
    _pointerLayer.strokeColor = [UIColor redColor].CGColor; // 红色边框
    _pointerLayer.lineWidth = 2.0;
    
    // 初始位置设置为0度（根据新的圆弧起始角度）
    _pointerLayer.affineTransform = CGAffineTransformMakeRotation([self angleForSpeed:0]);
    
    [self.layer addSublayer:_pointerLayer];
}

- (void)createSpeedLabel {
    _speedLabel = [[UILabel alloc] init];
    _speedLabel.text = @"0";
    _speedLabel.textColor = [UIColor whiteColor];
    _speedLabel.font = [UIFont systemFontOfSize:110 weight:UIFontWeightMedium]; // 指定字体大小和重量
    _speedLabel.textAlignment = NSTextAlignmentCenter;
    _speedLabel.adjustsFontSizeToFitWidth = YES; // 自动调整字体大小以适应宽度
    _speedLabel.minimumScaleFactor = 0.5; // 最小缩放比例
    [self addSubview:_speedLabel];
}

- (void)createUnitLabel {
    _unitLabel = [[UILabel alloc] init];
    _unitLabel.text = @"km/h";
    _unitLabel.textColor = [UIColor whiteColor];
    
    // 创建斜体字体
    UIFontDescriptor *fontDescriptor = [UIFontDescriptor fontDescriptorWithFontAttributes:@{
        UIFontDescriptorFamilyAttribute: @"System",
        UIFontDescriptorTraitsAttribute: @{UIFontWeightTrait: @(UIFontWeightRegular)}
    }];
    
    UIFontDescriptor *italicDescriptor = [fontDescriptor fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitItalic];
    UIFont *italicFont = [UIFont fontWithDescriptor:italicDescriptor size:16];
    
    // 如果上面的方法不生效，使用系统斜体字体
    if (!italicFont) {
        italicFont = [UIFont italicSystemFontOfSize:16];
    }
    
    _unitLabel.font = italicFont;
    _unitLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:_unitLabel];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    _gradientLayer.frame = self.bounds;
    
    // 更新圆弧路径
    [self updateArcPaths];
    
    // 更新指针路径
    [self updatePointerPath];
    
    // 布局标签
    CGFloat centerY = CGRectGetMidY(self.bounds);
    
    // 速度标签布局
    _speedLabel.frame = CGRectMake(20, centerY - 70, self.bounds.size.width - 40, 120);
    
    // 单位标签布局在速度标签下方
    _unitLabel.frame = CGRectMake(20, centerY + 50, self.bounds.size.width - 40, 25);
}

- (void)updateArcPaths {
    CGFloat radius = MIN(self.bounds.size.width, self.bounds.size.height) * 0.4;
    CGPoint center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
    
    CGFloat startAngle = M_PI * 45 / 180;
    CGFloat endAngle = M_PI * 315 / 180;
    
    UIBezierPath *arcPath = [UIBezierPath bezierPathWithArcCenter:center
                                                           radius:radius
                                                       startAngle:startAngle
                                                         endAngle:endAngle
                                                        clockwise:YES];
    
    _backgroundArcLayer.path = arcPath.CGPath;
    _speedArcLayer.path = arcPath.CGPath;
}

- (void)updatePointerPath {
 
    CGFloat radius = MIN(self.bounds.size.width, self.bounds.size.height) * 0.4;
    CGPoint center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));

    // 创建指针路径
    UIBezierPath *pointerPath = [UIBezierPath bezierPath];

    // 指针长度：从中心到圆弧边缘
    CGFloat pointerLength = radius;

    // 指针尖端（指向圆弧边缘）
    CGPoint tipPoint = CGPointMake(pointerLength, 0); // 相对于中心点的位置

    // 指针尾部宽度
    CGFloat tailWidth = 3.0;
    CGFloat tailLength = 70.0; // 尾部长度

    CGPoint tailPoint1 = CGPointMake(tailLength, -tailWidth/2);
    CGPoint tailPoint2 = CGPointMake(tailLength, tailWidth/2);

    [pointerPath moveToPoint:tailPoint1];
    [pointerPath addLineToPoint:tipPoint];
    [pointerPath addLineToPoint:tailPoint2];
    [pointerPath closePath];

    _pointerLayer.path = pointerPath.CGPath;

    // 关键：设置指针的position为中心点，anchorPoint为默认的(0.5,0.5)
    _pointerLayer.position = center;
    _pointerLayer.anchorPoint = CGPointMake(0.5, 0.5); // 确保以图层中心旋转
}

// 根据速度计算角度（0-180km/h 对应 45°到315°）
- (CGFloat)angleForSpeed:(CGFloat)speed {
    // 速度范围：0-180km/h
    // 角度范围：45°到315°
    CGFloat startAngle = M_PI * 45 / 180;  // 45°
    CGFloat endAngle = M_PI * 315 / 180;   // 315°
    
    // 计算速度对应的角度
    CGFloat speedRatio = speed / _maxSpeed;
    CGFloat angle = startAngle + (endAngle - startAngle) * speedRatio;
    
    // 确保角度在有效范围内
    angle = MAX(startAngle, MIN(endAngle, angle));
    
    return angle;
}

// 限制角度在45°-315°范围内
- (CGFloat)clampAngle:(CGFloat)angle {
    CGFloat minAngle = M_PI * 45 / 180;  // 45°
    CGFloat maxAngle = M_PI * 315 / 180; // 315°
    
    // 如果角度超出范围，限制在边界内
    if (angle < minAngle) return minAngle;
    if (angle > maxAngle) return maxAngle;
    return angle;
}

// 可靠的指针动画方法
- (void)animatePointerToAngle:(CGFloat)targetAngle duration:(CFTimeInterval)duration {
    // 移除之前的动画，重置状态
    [_pointerLayer removeAllAnimations];
    _pointerLayer.transform = CATransform3DMakeRotation([self currentPointerAngle], 0, 0, 1);
    
    CGFloat currentAngle = [self currentPointerAngle];
    if (self.pointerLastValue) {
        currentAngle = self.pointerLastValue;
    }
    targetAngle = [self clampAngle:targetAngle];
        
    // 创建动画
    CABasicAnimation *pointerAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    pointerAnimation.fromValue = @(currentAngle);
    pointerAnimation.toValue = @(targetAngle);
    pointerAnimation.duration = duration;
    pointerAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    
    // 关键设置：确保动画完成后的状态正确
    pointerAnimation.fillMode = kCAFillModeForwards;
    pointerAnimation.removedOnCompletion = NO;
    self.pointerLastValue = targetAngle;
    // 先设置最终状态
    _pointerLayer.transform = CATransform3DMakeRotation(targetAngle, 0, 0, 1);
    
    // 添加动画
    [_pointerLayer addAnimation:pointerAnimation forKey:@"pointerRotation"];
}

- (void)setSpeed:(CGFloat)speed {
    _speed = MIN(MAX(speed, 0), _maxSpeed);
    [self updateSpeedDisplay];
}

- (void)setSpeed:(CGFloat)speed animated:(BOOL)animated {
    [self setSpeed:speed animated:YES completion:nil];
}

- (void)setSpeed:(CGFloat)speed
        animated:(BOOL)animated
      completion:(void (^ __nullable)(BOOL finished))completion {

    _speed = MIN(MAX(speed, 0), _maxSpeed);
    self.animationCompletion = completion;
    // 先更新指针的变换，确保位置正确
    CGFloat targetAngle = [self angleForSpeed:_speed];
    
    if (animated) {
        // 圆弧动画
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
        animation.fromValue = @(_speedArcLayer.strokeEnd);
        animation.toValue = @(_speed / _maxSpeed);
        animation.duration = [self animationDurationFromSpeed:_speed];
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
        animation.delegate = self;
        _speedArcLayer.strokeEnd = _speed / _maxSpeed;
        [_speedArcLayer addAnimation:animation forKey:@"speedAnimation"];
        
        // 使用智能指针动画
        [self animatePointerToAngle:targetAngle
                           duration:[self animationDurationFromSpeed:_speed]];
    } else {
        _speedArcLayer.strokeEnd = _speed / _maxSpeed;
        _pointerLayer.transform = CATransform3DMakeRotation(targetAngle, 0, 0, 1);
    }
    
    [self updateSpeedDisplay];
}

#pragma mark -- CAAnimationDelegate
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    if ([((CABasicAnimation *)anim).keyPath isEqualToString:@"strokeEnd"] && flag) {
        if (self.animationCompletion) {
            self.animationCompletion(flag);
            self.animationCompletion = nil;
        }
    }
}

// 动画时长
- (CFTimeInterval)animationDurationFromSpeed:(CGFloat)speed {
    NSInteger currentSpeed = [self.speedLabel.text integerValue];
    
    NSInteger xcSpeed = speed - currentSpeed; // 目标速度和当前速度差值
    NSInteger absoluteValue = labs(xcSpeed); // 速度差值的绝对值
    
    return absoluteValue / 20 * 0.1; // 每 20 km/h 动画 0.1 秒
}

// 获取当前指针角度
- (CGFloat)currentPointerAngle {
    // 从transform中提取当前角度
    return atan2(_pointerLayer.transform.m12, _pointerLayer.transform.m11);
}

- (void)updateSpeedDisplay {
    _speedLabel.text = [NSString stringWithFormat:@"%.0f", _speed];
}


// 新增：播放启动动画（从0到180）
- (void)playStartupAnimation {
    [self playStartupAnimationWithCompletion:nil];
}

- (void)playStartupAnimationWithCompletion:(void (^)(BOOL))completion {
    if (_hasPlayedStartupAnimation) return;
    
    _hasPlayedStartupAnimation = YES;
    
    // 重置到初始状态
    _speedArcLayer.strokeEnd = 0;
    _pointerLayer.transform = CATransform3DMakeRotation([self angleForSpeed:0], 0, 0, 1);
    _speedLabel.text = @"0";
    __weak typeof(self)weakSelf = self;
    // 延迟一会儿开始动画，让视图完全加载
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self setSpeed:self.maxSpeed animated:YES completion:^(BOOL finished) {
            if (finished) {
                // 动画完成后回到0
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf setSpeed:0 animated:YES completion:^(BOOL finished) {
                        if (completion) {
                            completion(finished);
                        }
                    }];
                });
            }
        }];
    });
}

@end
